package cc.sunni.sell.controller;

import cc.sunni.sell.dto.OrderDto;
import cc.sunni.sell.enums.ResultEnum;
import cc.sunni.sell.exception.RRException;
import cc.sunni.sell.service.OrderMasterService;
import cc.sunni.sell.service.PayService;
import com.lly835.bestpay.model.PayResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

/**
 * @author jl
 * @since 2021/1/20 20:31
 */
@Controller
@RequestMapping("/pay")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class PayController {
    private final OrderMasterService orderMasterService;
    private final PayService payService;

    @GetMapping("/create")
    public ModelAndView create(@RequestParam("orderId") String orderId, @RequestParam("returnUrl") String returnUrl, Map<String, Object> map) {
        // 查询订单
        OrderDto orderDTO = orderMasterService.findOne(orderId);
        if (orderDTO == null) {
            throw new RRException(ResultEnum.ORDER_NOT_EXIST);
        }

       // 发起支付
        PayResponse payResponse = payService.create(orderDTO);

        map.put("payResponse", payResponse);
        map.put("returnUrl", returnUrl);

        return new ModelAndView("pay/create", map);
    }


    /**
     * 微信异步通知
     */
    @PostMapping("/notify")
    public ModelAndView notify(@RequestBody String notifyData) {
        payService.notify(notifyData);

        //返回给微信处理结果
        return new ModelAndView("pay/success");
    }
}
